package com.blb.community.Utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 验证码图片生成
 */
public class CodeUtiles {
    private static char[] arr="QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray();
//    private static int[] arr={0,1,2,3,4,5,6,7,8,9};
    private static Random random=new Random();
    private static int width=240;
    private static int height=65;

    public static Map<String, Object> getCodeImage() throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        //创建图片对象
        BufferedImage bufferedImage = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
        //根据图片对象创建画布
        Graphics graphics = bufferedImage.getGraphics();
        //设置画布的背景颜色
        graphics.setColor(Color.lightGray);
        graphics.fillRect(0,0,width,height);
        //设置字体样式
        Font font = new Font("微软雅黑",Font.BOLD,45);
        graphics.setFont(font);
        //设置字体数据并写在画布上
        String str = "";
        for (int i = 1; i <=4; i++) {
            String temp=arr[random.nextInt(arr.length)]+"";
            str+=temp;
            //随机字体颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            graphics.setColor(color);
            graphics.drawString(temp,46*i,random.nextInt(11)+45);
        }
       //画线
        for (int i = 0; i < 6; i++) {
            //随机画线颜色
            Color color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
            graphics.setColor(color);
            graphics.drawLine(random. nextInt(width),random. nextInt(height),random. nextInt(width),random. nextInt(height));
        }
        map.put("code", str);
        map.put("img", bufferedImage);
        return map;
    }
}
